package com.M10.BE.inventory;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.M10.BE.R;
import com.M10.BE.adapter.NullStringToEmptyAdapterFactory;
import com.M10.BE.database.TableAsset;
import com.M10.BE.database.TableInventory;
import com.M10.BE.entity.DownInventoryDetail;
import com.M10.BE.entity.InventoryDetail;
import com.M10.BE.entity.NAsset;
import com.M10.BE.fragment.AssetLostListFragment;
import com.M10.BE.fragment.DialogFragment;
import com.M10.BE.fragment.ToCheckFragment;
import com.fn.useries.UHFApplication;
import com.fn.useries.model.ResponseHandler;
import com.fn.useries.operation.U8Series;
import com.fn.useries.reader.model.InventoryBuffer;
import com.fn.useries.utils.PreferenceUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/17.
 */

public class DoInventoryActivity extends FragmentActivity {
    public static final String TAG = "DoInventoryActivity";
    @BindView(R.id.mytabhost)
    FragmentTabHost tabHost;
    @BindView(R.id.tv_inve_back)
    TextView tv_back;
    @BindView(R.id.tv_inve_orderid)
    TextView tv_inve_orderid;
    @BindView(R.id.tv_inve_dept)
    TextView tv_inve_dept;
    @BindView(R.id.tv_inve_producttype)
    TextView tv_inve_producttype;
    @BindView(R.id.tv_inve_rfidtype)
    TextView tv_inve_labeltype;
    @BindView(R.id.tv_inve_setime)
    TextView tv_inve_setime;
    @BindView(R.id.tv_inve_jine)
    TextView tv_inve_jine;
    @BindView(R.id.tv_inve_total)
    TextView tv_inve_total;
    @BindView(R.id.tv_inve_checkednum)
    TextView tv_inve_checkednum;
    @BindView(R.id.tv_start_inve)
    TextView tv_inve_start;
    @BindView(R.id.tv_stop_inve)
    TextView tv_inve_stop;
    @BindView(R.id.tv_finish_inve)
    TextView tv_inve_finish;
    private LayoutInflater inflater;
    private String myTabText[];
    private HashMap<String, Fragment> fragments = new HashMap<>();
    private Class fragmentArray[] = {
            ToCheckFragment.class, AssetLostListFragment.class
    };
    private Context context;
    String inventoryID;
    Gson gson;
    InventoryDetail inventoryDetail = null;
    DownInventoryDetail downInventoryDetail = null;
    private AlertDialog alert;
    private final CharSequence[] models = {"RFID", "二维码"};
    private U8Series mUSeries;
    List<NAsset> nAssets = null;//数据库查询的待盘资产

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_inventory);
        ButterKnife.bind(this);
        context = DoInventoryActivity.this;
        inventoryID = getIntent().getStringExtra("inventoryId");
        gson = new GsonBuilder().serializeNulls().
                registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        initView();
//        getDetail(inventoryID);
        new ReadInve(context).execute();
    }

    private void initView() {
        inflater = LayoutInflater.from(this);
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        for (int i = 0; i < 2; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(i + "").setIndicator(getTabView(i));
            tabHost.addTab(tabSpec, fragmentArray[i], null);
        }
        tabHost.getTabWidget().setBackgroundColor(Color.argb(80, 255, 255, 2555));
        tabHost.setCurrentTab(0);

    }

    @OnClick(R.id.tv_inve_back)
    public void onViewClicked() {
        finish();
    }

    @OnClick(R.id.tv_start_inve)
    public void startInveClick() {
        myShowDialog("请选择盘点方式", models, 0);
    }

    @OnClick(R.id.tv_stop_inve)
    public void stopInveClick() {
        saveTolocal();
    }

    @OnClick(R.id.tv_finish_inve)
    public void finishInveClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(DoInventoryActivity.this);
        builder.setMessage("是否结束盘点");
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //上传盘点单
                AlertDialog.Builder builderUpload = new AlertDialog.Builder(DoInventoryActivity.this);

                AlertDialog dialog_upload = builderUpload.create();
                dialog_upload.show();
                AlertDialog.Builder builder = new AlertDialog.Builder(DoInventoryActivity.this);
                builder.setTitle("提示");
                builder.setMessage("是否上传盘点结果");
                builder.setNegativeButton("稍后上传", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveTolocal();
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("立刻", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //上传盘点单
                        uploadInve();
                    }
                });
                AlertDialog dialog1 = builder.create();
                dialog1.show();
            }
        });
        AlertDialog dialog2 = builder.create();
        dialog2.show();


    }

    private void uploadInve() {
        List<UploadAsset> list = new ArrayList<>();
        for (int i = 0; i < downInventoryDetail.getList().size(); i++) {
            NAsset asset = downInventoryDetail.getList().get(i);
            UploadAsset uploadAsset = new UploadAsset();
            uploadAsset.setCardId(asset.getCardId());
            uploadAsset.setJudgeCount(asset.getCnum());
            uploadAsset.setLabelId(asset.getLabelId());
            uploadAsset.setQueryCount(asset.getjCount());
            list.add(uploadAsset);
        }
        String jsonString = new Gson().toJson(list);
        uploadInventory(downInventoryDetail, jsonString);
    }


    //将当前盘点信息保存到本地
    private void saveTolocal() {
        String jsonString = new Gson().toJson(downInventoryDetail);
        PreferenceUtils.write(DoInventoryActivity.this, "assets", "downinventory", jsonString);
        String a = PreferenceUtils.readString(DoInventoryActivity.this, "assets", "downinventory");
        DownInventoryDetail d = gson.fromJson(a, DownInventoryDetail.class);
        Toast.makeText(DoInventoryActivity.this, "已成功保存盘点信息", Toast.LENGTH_SHORT).show();
    }

    private View getTabView(int index) {
        myTabText = new String[]{
                "待盘资产", "已盘资产"
        };
        View view;
        view = LayoutInflater.from(DoInventoryActivity.this).inflate(R.layout.fragment_relation_tab_view, null);
        TextView tabTextView = (TextView) view.findViewById(R.id.relation_tab);
        tabTextView.setText(myTabText[index]);
        return view;
    }

    private void setViewValue(DownInventoryDetail inventoryDetail) {
        tv_inve_orderid.setText(inventoryDetail.getId());
        tv_inve_dept.setText(inventoryDetail.getOrgName());
//        tv_inve_producttype.setText(inventoryDetail.getQueryLabelType()=="0"?"RFID标签":"普通标签");
        tv_inve_labeltype.setText(inventoryDetail.getQueryLabelType() == "0" ? "RFID标签" : "普通标签");
        tv_inve_setime.setText(inventoryDetail.getSETime());
        tv_inve_jine.setText(inventoryDetail.getSEAmount());
        tv_inve_total.setText(inventoryDetail.getQueryCount());
//        tv_inve_checkednum.setText(inventoryDetail.getJudgeCount());
    }

    private void myShowDialog(final String titleName,
                              final CharSequence[] items, int selected) {
        // int saved = sp.getInt(key, selected);
        int saved = selected;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(titleName);
        builder.setSingleChoiceItems(items, saved,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        //rfid扫描
                        if (item == 0) {
                            rfidScan();
                        } else {

                        }
                        alert.dismiss();
                    }
                });

        alert = builder.create();
        alert.show();
    }
//    Id
//            judgeDate
//    judgeUser
//            queryCount
//    judgeCount
//            result
//cardId
//        labelId
//    queryCount
//            judgeCount

    public void uploadInventory(DownInventoryDetail downInventoryDetail, String result) {
        OkGo.<String>get(UHFApplication.BASE_HEAD + "judge/APPUpload")
                .tag(this)
                .params("id", downInventoryDetail.getId())
                .params("judgeDate", System.currentTimeMillis())
                .params("judgeUser", downInventoryDetail.getJudgeUser())
                .params("judgeCount", downInventoryDetail.getList().size())
                .params("queryCount", downInventoryDetail.getList().size())
                .params("result", result)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject object = new JSONObject(response.body());
                            String errcode = object.getString("statusCode");
                            String msg = object.getString("msg");
                            if ("0".equals(errcode)) {
                                String result = object.getString("result");
                                //删除记录
                                PreferenceUtils.write(DoInventoryActivity.this, "assets", "downinventory", null);
                                Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }
                });
    }

    private void rfidScan() {
        try {
////                mRefreshTime = new Date().getTime();
//                U8Series.setContext(MainActivity.this);
            mUSeries = U8Series.getInstance();

            mUSeries.startInventory(new ResponseHandler() {

                @Override
                public void onFailure(String msg) {
                    super.onFailure(msg);
                    Log.e("U8", msg);
                    Toast.makeText(DoInventoryActivity.this, getResources().getText(R.string.Disk_failure) + msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(String msg, Object data, byte[] parameters) {
                    super.onSuccess(msg, data, parameters);
                    if (msg.equals(U8Series.REFRESHTEXT)) {
//                            refreshText();
                        Log.e(TAG, "refreshText: " + msg);
                    } else if (msg.equals(U8Series.REFRESHLIST)) {
                        List<InventoryBuffer.InventoryTagMap> tagMapList =
                                (List<InventoryBuffer.InventoryTagMap>) data;
                        for (int i = 0; i < tagMapList.size(); i++) {
                            Log.e("list", i + ">>>>>>" + tagMapList.get(i).strEPC + "-------" + tagMapList.get(i).strCRC);
                            String tagId = tagMapList.get(i).strCRC;

                            for (int j = 0; j < nAssets.size(); j++) {
                                if (nAssets.get(j).getCardId().equals(tagId)) {
                                    downInventoryDetail.getList().add(nAssets.get(j));
                                    Message message1 = new Message();
                                    message1.obj = downInventoryDetail.getList();
                                    if (ToCheckFragment.mHandler != null) {
                                        ToCheckFragment.mHandler.sendMessage(message1);
                                    }
                                }
                            }
                        }
//                            inventoryTagData.clear();
//                            inventoryTagData.addAll((Collection<? extends InventoryBuffer.InventoryTagMap>) data);
//                            inventoryAdapter.notifyDataSetChanged();
                    } else {
                        Log.e("U8", "盘询成功,返回标识异常");
//                            System.out.println("盘询成功,返回标识异常");
                    }
                }

            });
//                mHandler.postDelayed(mRefreshRunnable, 500);
//                btnStart.setEnabled(false);
//                btnStop.setEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Exception", "盘询成功,返回标识异常");
        }

    }

    private class ReadInve extends AsyncTask<Void, Void, List<DownInventoryDetail>> {
        private Context context;

        public ReadInve(Context context) {
            this.context = context;
        }

        @Override
        protected List<DownInventoryDetail> doInBackground(Void... voids) {
            List<DownInventoryDetail> downInventoryDetails = TableInventory.searchInventory(context);
            if (downInventoryDetails != null && downInventoryDetails.size() > 0) {
                DownInventoryDetail downInventoryDetail = downInventoryDetails.get(0);
                List<NAsset> assets = TableAsset.searchAsset(context);
                downInventoryDetail.setList(assets);
            }
            return downInventoryDetails;
        }

        @Override
        protected void onPostExecute(List<DownInventoryDetail> downInventoryDetails) {
            super.onPostExecute(downInventoryDetails);
            if (downInventoryDetails != null && downInventoryDetails.size() > 0) {
                downInventoryDetail = downInventoryDetails.get(0);
                setViewValue(downInventoryDetail);
                nAssets = downInventoryDetail.getList();
//                Message message1 = new Message();
//                message1.obj = nAssets;
//                if (ToCheckFragment.mHandler != null) {
//                    ToCheckFragment.mHandler.sendMessage(message1);
//                }
            }
        }
    }

    private class UploadAsset {
        public String getCardId() {
            return cardId;
        }

        public void setCardId(String cardId) {
            this.cardId = cardId;
        }

        public String getLabelId() {
            return labelId;
        }

        public void setLabelId(String labelId) {
            this.labelId = labelId;
        }

        public String getQueryCount() {
            return queryCount;
        }

        public void setQueryCount(String queryCount) {
            this.queryCount = queryCount;
        }

        public String getJudgeCount() {
            return judgeCount;
        }

        public void setJudgeCount(String judgeCount) {
            this.judgeCount = judgeCount;
        }

        private String cardId;//	资产ID
        private String labelId;//	标签ID
        private String queryCount;//	资产数量
        private String judgeCount;//	盘点数量

    }
}
